package com.bitejiuyeke.job_publish.controller;

import com.bitejiuyeke.job_publish.common.AppResult;
import com.bitejiuyeke.job_publish.common.PageResult;
import com.bitejiuyeke.job_publish.common.ResultCode;
import com.bitejiuyeke.job_publish.config.AppConfig;
import com.bitejiuyeke.job_publish.config.RabbitMQConfig;
import com.bitejiuyeke.job_publish.controller.params.OfferModifyStateDTO;
import com.bitejiuyeke.job_publish.controller.params.OfferPageByUserDTO;
import com.bitejiuyeke.job_publish.enums.OfferStateEnum;
import com.bitejiuyeke.job_publish.enums.SendRecordStateEnum;
import com.bitejiuyeke.job_publish.model.Job;
import com.bitejiuyeke.job_publish.model.Offer;
import com.bitejiuyeke.job_publish.model.User;
import com.bitejiuyeke.job_publish.mq.model.OfferedMQ;
import com.bitejiuyeke.job_publish.service.IOfferService;
import com.bitejiuyeke.job_publish.utils.StringUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.PositiveOrZero;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @Author 比特就业课
 */
// API描述
@Tag(name = "Offer操作相关接口")
// Controller注解，返回的对象用JSON形式表示
@RestController
// 路径映射
@RequestMapping("/offer")
public class OfferController {

    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private IOfferService service;
    @Operation(summary = "更新Offer状态")
    @PostMapping("/state")
    public AppResult modifyState (HttpServletRequest request,
                                  @Validated @RequestBody OfferModifyStateDTO param){
        // 获取用户Id
        Long userId = (Long) request.getAttribute(AppConfig.TOKEN_USER_ID);
        // 查询Offer详情,获取职位信息
        Offer offer = service.selectById(param.getId());
        if (offer.getUserId() != userId) {
            return AppResult.failed(ResultCode.FAILED_NOT_PERMISSION);
        }
        // 更新对象
        Offer update = new Offer();
        update.setId(param.getId());
        update.setUserId(userId);
        update.setState(param.getState());
        service.modifyState(update);

        // 接受后发邮件
        if (OfferStateEnum.valueOf(param.getState()) == OfferStateEnum.ACCEPTED) {
            User user = offer.getSendRecord().getJob().getPublisher();
            if (!StringUtils.isEmpty(user.getEmail())) {
                // 消息队列-发送邮件
                Job job = offer.getSendRecord().getJob();
                OfferedMQ offeredMQ = new OfferedMQ();
                offeredMQ.setTargetNum(user.getEmail());
                offeredMQ.setStateEnum(SendRecordStateEnum.ACCEPTED);
                String content = "您发布的职位: " + job.getTitle() + ", 邀约状态已更新为: "
                        + SendRecordStateEnum.ACCEPTED.getMessage() + ". "
                        + "请登录比特校园兼职系统查看详情.";
                offeredMQ.setContent(content);
                // 发送消息
                rabbitTemplate.convertAndSend(RabbitMQConfig.BITE_JOB_EXCHANGE_NAME,
                        RabbitMQConfig.BITE_JOB_OFFERED_ROUTING_KEY, offeredMQ);
            }

        }
        return AppResult.success();
    }

    @Operation(summary = "根据Id获取Offer详情")
    @Parameter(name = "id", description = "Offer编号", in = ParameterIn.QUERY)
    @GetMapping("/details/{id}")
    public AppResult<Offer> selectById (HttpServletRequest request,
                                        @PositiveOrZero(message = "Offer编号不正确") @PathVariable("id") Long id) {
        // 获取当前用户
        Long userId = (Long) request.getAttribute(AppConfig.TOKEN_USER_ID);
        // 查询Offer
        Offer offer = service.selectById(id);
        if (offer == null) {
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        if (offer.getUserId() != userId && offer.getSendRecord().getReceiveUserId() != userId) {
            return AppResult.failed(ResultCode.FAILED_NOT_PERMISSION);
        }

        return AppResult.success(offer);
    }

    @Operation(summary = "根据用户信息查询OFFER记录")
    @GetMapping("/pageByUser")
    public AppResult<PageResult> selectPageByUser (HttpServletRequest request,
                                       @Validated OfferPageByUserDTO param) {
        Long userId = null;
        if (param.getUserId() == null) {
            userId = (Long) request.getAttribute(AppConfig.TOKEN_USER_ID);
        }
        // 获取当前用户
        param.setUserId(userId);
        // 条件对象
        Offer offer = new Offer();
        BeanUtils.copyProperties(param, offer);
        // 查询结果
        PageResult<Offer> pageResult = service.selectPageByUser(offer);
        // 返回
        return AppResult.success(pageResult);
    }
}
